import JSZip from 'jszip'
import fileSaver from 'file-saver'
import axios from 'axios'
import {Loading} from 'quasar'

let state = null;

const getFile = (url, _state) => {
  state = _state;
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer',
      onDownloadProgress: onDownloadProgress
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    });
    if(state) state.commit('resetDownload');
    lastTime = null;
  })
};

let lastProgress = 0;
let lastTime = new Date().getTime();
let downloadSpeed = 0;
function onDownloadProgress(progress) {
  if(!state) return;
  const currentTime = new Date().getTime();
  if(!lastTime || currentTime - lastTime > 1000) {
    downloadSpeed = (progress.loaded - lastProgress) / ((currentTime - lastTime) / 1000);
    lastProgress = progress.loaded;
    lastTime = currentTime;
  }
  state.commit('setDownloadProgress', progress.loaded);
  state.commit('setDownloadTotal', progress.total);
  state.commit('setDownloadSpeed',
    `${(downloadSpeed > 1024 * 1024) ?
    `${Math.round(downloadSpeed / 1024 / 1024 * 100) / 100}MB/s` :
    `${Math.round(downloadSpeed / 1024 * 100) / 100}KB/s`}`)
}

export async function handleBatchDownload(url, state) {
  let data;
  await getFile(url, state).then(res => {
    data = res;
  }).catch(error => {
    throw error;
  })
  return data;
}

export async function createLocalPack(audio, cover, mapContent, title, artist, author, difficulty) {
  const zip = new JSZip();
  zip.file('audio', audio, {binary: true});
  zip.file('cover', cover, {binary: true});
  zip.file('chart.json', JSON.stringify({title, artist, author, difficulty, mapContent}));
  await zip.generateAsync({type: "blob"}).then(function (content) {
    saveAs(content, `${title}.bangpack`);
  })
}

export async function loadLocalPack(file) {
  const zip = new JSZip();
  let audio, cover, chart;
  await zip.loadAsync(file).then(async function (file) {
    await zip.file('audio').async('blob').then(content => audio = content);
    await zip.file('cover').async('blob').then(content => cover = content);
    await zip.file('chart.json').async('text')
      .then(function (content) {
        chart = JSON.parse(content);
      });
  })
  let {title, artist, author, difficulty, mapContent} = chart;
  return {audio, cover, title, artist, author, difficulty, mapContent};
}
